/*
 * =====================================================================================
 *
 *       Filename:  trace.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2015-08-17 07:19:20 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:   (), 
 *        Company:  
 *
 * =====================================================================================
 */

#include "Trace.h"
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <string.h>
#include <stdarg.h>
typedef long _longtime;
/////////////////////////////////////////////////////////////////

// logger

#define LOG_FILE	"./jslpnr.log"		// /var/log is the log file director in linux convention
#define BKUP_FILE	"/var/log/jslpnr.bak"		// for embedded linux system, /var/log

#define MAX_LOGSIZE 40000000
const char* time_stamp()
{
	static char timestr[64];
#ifdef linux
	char *p = timestr;
	struct timeval tv;
	gettimeofday( &tv, NULL );

	strftime( p, sizeof(timestr), "%y/%m/%d %H:%M:%S", localtime( &tv.tv_sec ) );
	sprintf( p + strlen(p), ".%03lu", tv.tv_usec/1000 );

#else
		SYSTEMTIME	tnow;
		GetLocalTime( &tnow );
		sprintf( timestr, "%04d/%02d/%02d %02d:%02d:%02d.%03d", 
					tnow.wYear, tnow.wMonth, tnow.wDay, 
					tnow.wHour, tnow.wMinute, tnow.wSecond, tnow.wMilliseconds );
#endif
	return timestr;
}

void trace_log(const char *fmt,...)
{
	va_list		va;
	char		str[1024 ] = "";
	FILE *fp;
	
	va_start(va, fmt);
	vsprintf(str, fmt, va);
	va_end(va);

	fp = fopen( LOG_FILE, "a" );
	if ( fp!=NULL && ftell(fp) > MAX_LOGSIZE )
	{
		fclose(fp);
		remove( BKUP_FILE );
		rename( LOG_FILE, BKUP_FILE );
		fp = fopen( LOG_FILE, "a" );
	}
	if ( fp != NULL )
	{
		if ( fmt[0] != '\t' )
			fprintf(fp, "[%s] %s", time_stamp(), str );
		else
			fprintf(fp, "%26s%s", " ", str+1 );
		fclose(fp);
	}
}

static const time_t _secondOffset = ( 365 * 31 + 8 ) * 24 * 60 * 60;
_longtime timeGetLongTime()
{
	struct timeval tv;
	if( gettimeofday( &tv, NULL ) )
	{
		return -1;
	}
	return (_longtime)(( tv.tv_sec - _secondOffset ) * 1000 + tv.tv_usec / 1000);
}
